var http = require('http'); 

let Sina = {

    keyWordSearch: (key, callback) => {
        $.get(`http://suggest3.sinajs.cn/suggest/type=&key=${key}`, (res) => {
            let data = [];
            if (res !== 'var suggestvalue="";') {
                res = res.replace('var suggestvalue="', '').replace('";', '');
                var arr = res.split(';');
                let flag = 0;
                for (var i=0; i<arr.length; i++) {
                    let detail = arr[i].split(',');
                    let single = {
                        sharesName: detail[0],
                        sharesCode: detail[3]
                    }
                    data.push(single);

                    flag ++ ;
                    if (flag > 10) {
                        break;
                    }
                }
            }
            callback(data);
        })
    },

    /**
     * items: [sh123123,sh123123,sh123123]
     */
    search(items, callback) {

        var req = http.get(`http://hq.sinajs.cn//list=${items.join(',')}`,(res) => { 
            res.setEncoding('utf8');
            let dataRes = [];
            let dataResLength = 0;
            res.on('data', function (chunk) { 
                dataRes = dataRes + chunk;
                dataResLength =dataResLength + chunk.length;
            });
            res.on('end', function() {
                console.log(dataRes);
                let resObj = {};
                let dataArr = dataRes.split(';');
                if (dataArr.length > 0) {
                    for (let i=0; i<items.length; i++) {
                        let code = items[i];
                        let data = dataArr[i].replace(/\s+/g,"");
                        if (data !== `var hq_str_${code}=""` && data != '') {
                            data = data.replace(`varhq_str_${code}=`, '').replace('"', '');
                            let detail = data.split(',')
                            resObj[code] = {
                                startPrice: detail[2],
                                currentPrice: detail[3]
                            }
                        }
                    }
                    callback(resObj);
                }
            }); 
        }); 
           
        req.on('error', function (e) { 
            console.log('problem with request: ' + e.message); 
        }); 
    }
}

module.exports = Sina